
package net.anzix.jimposition.transformations;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.swing.JPanel;
import net.anzix.jimposition.BasicTransformation;

public class BookletFilter extends BasicTransformation{
   
    private JPanel panel = new NoSettingsPanel();
    public byte[] alter(byte[] input) {
         try {
            PdfReader inputReader = new PdfReader(input);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            Rectangle pageSize = inputReader.getPageSize(2);
            Document document = new Document(new Rectangle(pageSize.right()*2,pageSize.top()));
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
            document.open();
            int pageNo = 1;
            int maxPageNum = inputReader.getNumberOfPages();
            PdfContentByte cb = writer.getDirectContent();
            for (int page=1;page<=maxPageNum;page++){
                if (page%2==1) document.newPage();
                
                float offsetx=pageSize.right()*((page-1)%2);
                
                cb.addTemplate(writer.getImportedPage(inputReader, page),1f,0f,0f,1f,offsetx,0f);
                cb.stroke();
            }
            document.close();
            return outputStream.toByteArray();
        }catch(DocumentException ex){
            ex.printStackTrace();
            return null;
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }

    }
    public String toString() {
        return "Simple booklet (2 in 1)";
    }

    public void setPanelSettings() {
    }

    public void getPanelSettings() {
    }

    public JPanel getPanel() {
        return panel;
    }


   
}
